﻿using Unity.Netcode;
using UnityEngine;

namespace E.Tool
{
    public abstract class AutoComponent : NetworkBehaviour
    {
        [Tooltip("自动模式")] public AutoMode mode;
        [Tooltip("倒计时")] public float time = 1;
        [Tooltip("累计触发数量")] public int frequency = 1;
        [Tooltip("当前触发数量")] [SerializeField] protected int tmp;

        protected virtual void OnEnable()
        {
            switch (mode)
            {
                case AutoMode.激活时不执行:
                    break;
                case AutoMode.激活时立刻执行:
                    Do();
                    break;
                case AutoMode.激活时开始倒计时执行:
                    CancelInvoke();
                    Invoke(nameof(Do), time);
                    break;
                case AutoMode.激活时开始累计触发执行:
                    tmp = 0;
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 执行内容
        /// </summary>
        public abstract void Do();

        /// <summary>
        /// 检查计数
        /// </summary>
        /// <returns></returns>
        public bool CheckFrequencyDo()
        {
            if (tmp >= frequency)
            {
                Do();
                tmp = 0;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 增加计数一次
        /// </summary>
        [ContextMenu("触发一次")]
        public void AddOnce()
        {
            if (mode != AutoMode.激活时开始累计触发执行)
            {
                Debug.LogError("自动模式不匹配");
                return;
            }
            if (!enabled)
            {
                Debug.LogWarning("已暂停");
                return;
            }
            if (frequency < 1)
            {
                Debug.LogError("变量trigger不能小于1");
            }

            tmp++;
            CheckFrequencyDo();
        }

        /// <summary>
        /// 暂停执行
        /// </summary>
        public virtual void Pause()
        {
            enabled = false;
        }
        /// <summary>
        /// 继续执行
        /// </summary>
        public virtual void Continue()
        {
            enabled = true;
        }

        public enum AutoMode
        {
            激活时不执行,
            激活时立刻执行,
            激活时开始倒计时执行,
            激活时开始累计触发执行,
        }
    }
}